package com.easpeed.comon.dialog

import android.Manifest
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.easpeed.common.CommonConsts
import com.easpeed.comon.DataConsts
import com.easpeed.comon.bean.BaseData
import com.easpeed.comon.bean.CommonKeyValue
import com.easpeed.comon.bean.PhotoBean
import com.easpeed.comon.memorycache.CommonMemoryCache
import com.easpeed.comon.utils.setViewsOnclickListener
import com.easpeed.comon.widget.PhotoSelectView
import com.easpeed.elevator.R
import com.easpeed.elevator.databinding.DialogRouteBinding
import com.easpeed.elevator.utils.NoticeDialog
import com.easpeed.comon.photo.PhotoUtils
import com.easpeed.comon.utils.CacheHelper
import com.easpeed.comon.utils.CommonOperateUtils
import com.easpeed.comon.utils.ImageUtils
import com.easpeed.comon.utils.Line
import com.easpeed.comon.utils.NetHelper
import com.easpeed.comon.utils.Optical
import com.easpeed.comon.utils.Record
import com.easpeed.comon.utils.SocketHelper
import com.easpeed.comon.utils.UploadFile
import com.easpeed.comon.utils.transformBitmap
import com.easpeed.comon.utils.transformFile
import com.easpeed.comon.widget.ImageWatcher
import com.easpeed.elevator.bean.LineBean
import com.easpeed.elevator.bean.OpticalBean
import com.easpeed.elevator.bean.RouteBean
import com.easpeed.user.UserLoginActivity
import com.easpeed.user.dialog.UserDialogHelper
import com.easpeed.user.utils.FileHelper
import com.example.permission.IRejectedCallback
import com.example.permission.IResultCallback
import com.example.permission.PermissionHelper
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID


/**
 * Created by bigyu on 2024/11/12 13:37
 * com.easpeed.comon.dialog
 */
class RouteUploadDialog {
    var dialogEventTable: NoticeDialog? = null
    private val routeTypeViews = mutableListOf<View>()

    private var mContext: Context? = null
    val lineList = ArrayList<LineBean>()

    private var routeTypeId: String? = null
    private var photoUtils: PhotoUtils? = null

    private var currentLineId: String? = null
    private var currentLineName: String? = null
    private var currentOpticalId: String? = null
    private var currentOpticalName: String? = null

    private var imgList = ArrayList<String>()

    //光纤编号
    private var currentNumber: String? = null

    private var bean: RouteBean? = null
    private var callback: ((RouteBean, type: Int) -> Unit)? = null
    private var isUpdate: Boolean = false

    var binding: DialogRouteBinding? = null
    fun show(mContext: Context, bean: RouteBean, isUpdate: Boolean, callback: (RouteBean, type: Int) -> Unit) {
        this.isUpdate = isUpdate
        this.bean = bean
        this.callback = callback
        popwindowTokePhoto = PopwindowTokePhotoV2(mContext)
        photoUtils = PhotoUtils(mContext)

        this.mContext = mContext
        if (dialogEventTable == null) {
            dialogEventTable = NoticeDialog.Builder(mContext).setLayoutId(R.layout.dialog_route).setClickBtnDismissDialog(true).setCanCancel(true).setCanceledOnTouchOutside(true).create()
            dialogEventTable?.setOnclickListener(R.id.close, View.OnClickListener { v: View? ->
                dialogEventTable?.dismiss()
            })
            dialogEventTable?.setDialogWith((ScreenUtils.getScreenWidth() * 0.9f).toInt(), (ScreenUtils.getScreenHeight() * 0.9f).toInt())
            dialogEventTable?.setGravity(Gravity.CENTER)
        }

        if (dialogEventTable?.isShowing != true) {
            dialogEventTable?.show()
        }

        binding = dialogEventTable?.getView(R.id.root)?.let { DataBindingUtil.bind(it) }

        iniListener()

        initStep1View()
        initStep2View()
        initData()
        binding?.step1?.performClick()
        renderData()
    }


    private fun renderData() {
        routeTypeId = bean?.routeTypeId
        if (routeTypeId == "2") {
            routeTypeViews.lastOrNull()?.performClick()
        } else {
            routeTypeViews.firstOrNull()?.performClick()
        }
        currentLineId = bean?.lineId
        currentLineName = bean?.lineName
        currentOpticalId = bean?.opticalId
        currentOpticalName = bean?.opticalName
        currentNumber = bean?.codeMark


        bean?.imagePath?.forEach {
            binding?.photoSelectView?.addNewPhoto(imageUrl = it, bitmap = File(it).transformBitmap())
        }
        binding?.lineName?.text = currentLineName
        binding?.opticalName?.text = currentOpticalName
        binding?.numberName?.text = currentNumber
        binding?.addressRemark?.setText(bean?.addressRemark)
        binding?.routeRemark?.setText(bean?.routeRemark)
        binding?.distance?.setText(bean?.distance ?: "")
    }

    private var popwindowTokePhoto: PopwindowTokePhotoV2? = null
    private fun initData() {
//        lineList.clear()
//        lineList.addAll(FileHelper.readLineData(mContext))
        netForLineList()
    }

    private fun initStep2View() {
        if (isUpdate) {
            binding?.delete?.visibility = View.VISIBLE
        } else {
            binding?.delete?.visibility = View.GONE
        }
        binding?.delete?.setOnClickListener {
            UserDialogHelper.showNoticeDialog(mContext!!, "删除提示", "确定删除当前${DataConsts.getRouteType(bean?.routeTypeId)}吗？", {
                dialogEventTable?.dismiss()
                bean?.let { it1 ->

                    netForDeleteRecord(it1.routeId)
//                    callback?.invoke(it1, 0)
                }
            })
        }

        binding?.photoSelectView?.setImageClickListener { photoBean: PhotoBean?, type: Int, imageView ->
            when (type) {
                PhotoSelectView.TYPE_CLICK_PHOTO -> {

                    imageWatcher?.show(imageView, photoBean?.imageUrl)

                }

                PhotoSelectView.TYPE_DELETE_PHOTO -> {
                    //删除图片
                    photoBean?.let {
                        binding?.photoSelectView?.deletePhoto(photoBean)
                    }
                }

                PhotoSelectView.TYPE_NEW_PHOTO -> {
                    //添加一张图片
                    popwindowTokePhoto?.showChoose(dialogEventTable?.window?.decorView, width = CommonMemoryCache.getDialogMaxWidth()) {
                        if (Build.VERSION.SDK_INT >= 33) {
                            startPhoto(it)
                        } else {
                            startPhoto(it)
                        }
                    }
                }
            }
        }

        binding?.save?.setOnClickListener {
            if (routeTypeId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择标定点")
                return@setOnClickListener
            }
            if (currentLineId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择线路名称")
                return@setOnClickListener
            }
            if (currentOpticalId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择光缆名称")
                return@setOnClickListener
            }
            if (currentNumber.isNullOrEmpty()) {
                ToastUtils.showShort("请选择纤芯编号")
                return@setOnClickListener
            }


            imgList.clear()
            bean?.routeTypeId = routeTypeId
            bean?.routeType = DataConsts.getRouteType(routeTypeId)
            bean?.lineId = currentLineId
            bean?.lineName = currentLineName

            bean?.opticalId = currentOpticalId
            bean?.opticalName = currentOpticalName

            bean?.codeMark = currentNumber

            bean?.addressRemark = binding?.addressRemark?.text.toString()
            bean?.routeRemark = binding?.routeRemark?.text.toString()
            bean?.distance = binding?.distance?.text.toString()



            binding?.photoSelectView?.getAllImage()?.forEach {
//                val fileName = "${UUID.randomUUID()}.jpg"
//                val fileStr = File("${picRootPath}${File.separator}$fileName")
//                val result = it.bitmap.transformFile(fileStr)
                it.imageUrl?.let { it1 -> imgList.add(it1) }
            }

            bean?.imagePath?.clear()
            bean?.imagePath?.addAll(imgList)
            dialogEventTable?.dismiss()

            bean?.let { it1 ->

                if (it1.routeId.isNullOrEmpty()) {
                    netForCreateRecord(it1)
                } else {
                    netForUpdateRecord(it1)
                }
            }
        }
    }

    private fun startPhoto(it: Int) {
        val permissions = listOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        PermissionHelper.with(mContext as FragmentActivity)
            .permissions(permissions)
            .explainAfterRejected(object : IRejectedCallback {
                override fun onRejected(process: IRejectedCallback.IRejectedProcess, rejectedPermissions: List<String>) {
                    //当用户拒绝了某些权限后, 该回调先于IResultCallback#onResult回调，可以在这里弹出弹窗向用户解释被拒绝的权限对应用的必要性：
                    //process：用户同意再次申请权限时，调用process的相应方法，继续权限申请流程
                    //rejectedPermissions：被用户拒绝的权限
                }
            }).request(object : IResultCallback {
                override fun onResult(isAllGrant: Boolean, grantedPermissions: List<String>, rejectedPermissions: List<String>) {
                    //授权结果回调
                    if (isAllGrant) {
                        if (it == 0) {
                            photoUtils?.startCamera()
                        } else {
                            photoUtils?.choosePic()
                        }
                    }
                }
            })
    }


    private fun initStep1View() {
        routeTypeViews.clear()
        binding?.pointLayout?.addView(addViewFlexbox(paddingTop = 15).apply {
            text = DataConsts.getRouteType("1")
            tag = DataConsts.getRouteType("1")
            val drawableStart = ContextCompat.getColorStateList(mContext!!, R.color.color_blue_gray)
            setTextColor(drawableStart)
            routeTypeViews.add(this)
            setOnClickListener {
                routeTypeId = "1"
                routeTypeViews.forEach { it.isActivated = false }
                it.isActivated = true
            }
        })
        binding?.pointLayout?.addView(addViewFlexbox(paddingTop = 15).apply {
            text = DataConsts.getRouteType("2")
            tag = DataConsts.getRouteType("2")
            val drawableStart = ContextCompat.getColorStateList(mContext!!, R.color.color_blue_gray)
            setTextColor(drawableStart)
            routeTypeViews.add(this)
            setOnClickListener {
                routeTypeViews.forEach { it.isActivated = false }
                it.isActivated = true
                routeTypeId = "2"
            }
        })
        binding?.next?.setOnClickListener {
            if (routeTypeId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择标定点")
                return@setOnClickListener
            }
            binding?.step2?.performClick()
        }
    }


    private fun step1View() {

    }

    private fun step2View() {


    }

    var imageWatcher: ImageWatcher? = null

    private fun iniListener() {
        imageWatcher = ImageWatcher(mContext)
        imageWatcher?.apply {
            setStartBackGroundColor(Color.parseColor("#99000000"))
            setLoader { context, uri, lc ->
                Glide.with(context).load(uri)
                    .into(object : CustomTarget<Drawable?>() {

                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            lc.onLoadFailed(errorDrawable)
                        }

                        override fun onLoadCleared(placeholder: Drawable?) {
                        }

                        override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) {
                            lc.onResourceReady(resource)
                        }

                        override fun onLoadStarted(placeholder: Drawable?) {
                            lc.onLoadStarted(placeholder)
                        }
                    })
            }
        }
        (dialogEventTable?.window?.decorView as ViewGroup).addView(imageWatcher)

        //图片获取回调
        photoUtils?.setCallback { requestCode, resultCode, data ->
            photoUtils?.onActivityResult(requestCode, resultCode, data, object : PhotoUtils.PhotoResult {
                override fun photoResult(bitmap: Bitmap?) {
                    bitmap?.let {
                        val picRootPath = FileHelper.getPicturePath(mContext)
//                        netForUploadImage(AppFileUtils.saveImage(bitmap))
                        val fileName = "${UUID.randomUUID()}.jpg"
                        val fileStr = File("${picRootPath}${File.separator}$fileName")
                        val file = ImageUtils.compressImage(bitmap)
                        if (file != null) {
                            netForUploadImage(file.absolutePath)
                        }

//                        val result = bitmap.transformFile(fileStr)
//                        if (result) {
//                            netForUploadImage(fileStr.absolutePath)
//                        }

//                        if (result) {
//                            binding?.photoSelectView?.addNewPhoto(imageUrl = fileStr.absolutePath, bitmap = it)
//                        }
                    }
                }
            })
        }

        binding?.lineName?.setOnClickListener {
            val list = lineList.map {
                CommonKeyValue<String>(it.lineId, it.lineName)
            } as ArrayList<CommonKeyValue<String>>?
            if (list.isNullOrEmpty()) {
                ToastUtils.showShort("无线路数据，请前往线路管理添加")
                return@setOnClickListener
            }
            PopwindowDropSelect(mContext).showChoose(it, currentLineId, it.measuredWidth, opticalList = list, {
                val item = it.firstOrNull()
                currentLineId = item?.id
                currentLineName = item?.name

                currentOpticalId = ""
                binding?.lineName?.text = item?.name
                binding?.opticalName?.text = ""
                binding?.numberName?.text = ""
            }, {
                binding?.lineName?.isActivated = it != 0
            })
        }
        binding?.opticalName?.setOnClickListener {
            val list = lineList.find { it.lineId == currentLineId }?.opticalList?.map {
                CommonKeyValue<String>(it.id, it.name)
            } as ArrayList<CommonKeyValue<String>>?
            if (currentLineId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择线路名称")
                return@setOnClickListener
            }
            if (list.isNullOrEmpty()) {
                ToastUtils.showShort("线路下无光缆数据，请前往线路管理添加")
                return@setOnClickListener
            }
            PopwindowDropSelect(mContext).showChoose(it, currentOpticalId, it.measuredWidth, opticalList = list, {
                val item = it.firstOrNull()
                currentOpticalId = item?.id
                currentOpticalName = item?.name

                binding?.opticalName?.text = item?.name
            }, {
                binding?.opticalName?.isActivated = it != 0
            })
        }
        binding?.numberName?.setOnClickListener {
            val list = lineList.find { it.lineId == currentLineId }?.opticalList?.find { it.id == currentOpticalId }?.codeMark?.split("；")?.filter { !it.isEmpty() }?.map {
                CommonKeyValue<String>(it, it)
            } as ArrayList<CommonKeyValue<String>>?
            if (currentOpticalId.isNullOrEmpty()) {
                ToastUtils.showShort("请选择光缆名称")
                return@setOnClickListener
            }
            if (list.isNullOrEmpty()) {
                ToastUtils.showShort("当前光缆下无纤芯编号，请前往线路管理添加")
                return@setOnClickListener
            }
            PopwindowDropSelect(mContext, isSingle = false).showChoose(it, currentNumber, it.measuredWidth, opticalList = list, {
                currentNumber = it.joinToString(separator = "；") { it.name.toString() }
                binding?.numberName?.text = currentNumber
            }, {
                binding?.numberName?.isActivated = it != 0
            })
        }
        setViewsOnclickListener(binding?.step1, binding?.step2) {
            when (it) {
                binding?.step1 -> {
                    binding?.step1Text?.text = "1"
                    binding?.step1Text?.isActivated = true
                    binding?.step1TextContent?.isActivated = true
                    binding?.step1Layout?.visibility = View.VISIBLE
                    binding?.step1Text?.setTextColor(Color.parseColor("#FFFFFF"))


                    binding?.step2Text?.text = "2"
                    binding?.step2Text?.isActivated = false
                    binding?.step2TextContent?.isActivated = false
                    binding?.step2Layout?.visibility = View.GONE
                    step1View()
                }

                binding?.step2 -> {
                    if (routeTypeId.isNullOrEmpty()) {
                        ToastUtils.showShort("请选择标定点")
                        return@setViewsOnclickListener
                    }
                    binding?.step2Text?.text = "2"
                    binding?.step2Text?.isActivated = true
                    binding?.step2TextContent?.isActivated = true
                    binding?.step2Layout?.visibility = View.VISIBLE


                    binding?.step1Layout?.visibility = View.GONE
                    binding?.step1Text?.text = "√"
                    binding?.step1Text?.setTextColor(Color.parseColor("#18A0FB"))
                    binding?.step1Text?.isActivated = false
                    binding?.step1TextContent?.isActivated = false
                    step2View()
                }
            }
        }

    }

    private fun addViewFlexbox(paddingTop: Int = 10): TextView {
// 创建 TextView 实例
        val textView = TextView(mContext)
        // 设置 TextView 的属性
        textView.id = View.generateViewId()
        textView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,  // 宽度 0dp，使用百分比宽度
            LinearLayout.LayoutParams.WRAP_CONTENT // 高度包裹内容
        )

        textView.setTextColor(Color.parseColor("#E5E6EB"))
        textView.gravity = Gravity.CENTER_VERTICAL

        // 设置 TextView 的 drawableStart
        val drawableStart = ContextCompat.getDrawable(mContext!!, R.drawable.shape_check_icon)
        textView.setCompoundDrawablesWithIntrinsicBounds(drawableStart, null, null, null)
        textView.compoundDrawablePadding = 2

        // 设置 MarginTop
        val params = textView.layoutParams as MarginLayoutParams
        params.setMargins(0, SizeUtils.dp2px(paddingTop.toFloat()), 0, 0)
        return textView
    }


    private lateinit var netHelper: NetHelper


    private fun netForCreate(lineName: String?) {
        val map = HashMap<String, Any?>()
        map["lineName"] = "$lineName"
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForCreateRecord(true , map, Consumer<BaseData<Record>> {
            if (it.code == 200) {
                ToastUtils.showShort("上传成功")
            } else {
                ToastUtils.showShort("${it.message}")
            }

        })
    }

    private fun netForLineList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForLineList(isLoading = false, map, Consumer<BaseData<List<Line>>> {
            if (it.code == 200) {
                lineList.clear()
                it.data?.map {
                    LineBean().apply {
                        this.lineName = it.lineName
                        this.lineId = it.id.toString()
                    }
                }?.let { it1 -> lineList.addAll(it1) }
                netForOpticalList()
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForOpticalList() {
        val map = HashMap<String, Any>()
        map["deviceCode"] = CommonConsts.targetDeviceId
        map["userId"] = "${CacheHelper.instance().getStringValue("userId")}"
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        lineList.forEach {
            it.opticalList?.clear()
        }
        netHelper.netForListOptical(isLoading = false, map, Consumer<BaseData<List<Optical>>> {
            if (it.code == 200) {
                if (it.data != null) {
                    it.data?.forEach { data ->

                        lineList.find { it.lineId == data.lineId.toString() }?.let {
                            if (it.opticalList == null) {
                                it.opticalList = arrayListOf()
                            }
                            it.opticalList?.add(OpticalBean(data.id.toString()).apply {
                                this.remark = data.remark
                                this.length = data.fibreLength
                                this.codeMark = data.fibreCodes
                                this.number = data.fibreNum.toString()
                                this.zjd = data.hop
                                this.level = data.opticalLevel.toString()
                                this.name = data.opticalName
                                this.parentId = data.lineId.toString()
                            })
                        }
                    }
                }
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForCreateRecord(bean: RouteBean) {
        val map = HashMap<String, Any?>()
        map["lineId"] = bean.lineId
        map["opticalId"] = bean.opticalId
        map["recordType"] = bean.routeTypeId


        map["fibreCodes"] = bean.codeMark
        map["distance"] = bean.distance
        map["placeDesc"] = bean.addressRemark
        map["remark"] = bean.routeRemark
        map["latitude"] = bean.lat
        map["longitude"] = bean.lng
        map["deviceCode"] = CommonConsts.targetDeviceId

        bean.imagePath.takeIf {
            it.isNotEmpty()
        }?.let {
            map["pictures"] = bean.imagePath.joinToString(";")
        }

        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForCreateRecord(true  , map, Consumer<BaseData<Record>> {
            if (it.code == 200) {
                callback?.invoke(bean, 1)
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForUpdateRecord(bean: RouteBean) {
        val map = HashMap<String, Any?>()
        map["id"] = bean.routeId
        map["lineId"] = bean.lineId
        map["opticalId"] = bean.opticalId
        map["recordType"] = bean.routeTypeId


        map["fibreCodes"] = bean.codeMark
        map["distance"] = bean.distance
        map["placeDesc"] = bean.addressRemark
        map["remark"] = bean.routeRemark
        map["latitude"] = bean.lat
        map["longitude"] = bean.lng
        map["deviceCode"] = CommonConsts.targetDeviceId

        bean.imagePath.takeIf {
            it.isNotEmpty()
        }?.let {
            map["pictures"] = bean.imagePath.joinToString(";")
        }

        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForUpdateRecord(true  ,map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                callback?.invoke(bean, 1)
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForDeleteRecord(id: String?) {
        val map = HashMap<String, Any?>()
        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForDeleteRecord("$id", map, Consumer<BaseData<String>> {
            if (it.code == 200) {
                bean?.let { it1 -> callback?.invoke(it1, 0) }
            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }

    private fun netForUploadImage(filePath: String) {
        val file = File(filePath)
        if (!file.exists()) {
            ToastUtils.showShort("图片不存在")
            return
        }

//        val newFile = copyFileToTempDir(file, mContext!!)

        if (!::netHelper.isInitialized) {
            netHelper = NetHelper(mContext!!)
        }
        netHelper.netForUploadFile(true , file, Consumer<BaseData<UploadFile>> {
            if (it.code == 200) {
                binding?.photoSelectView?.addNewPhoto(imageUrl = it.data?.fileUrl, bitmap = null)

            } else {
                ToastUtils.showShort("${it.message}")
            }
        })
    }




}